// pages/map/index.js
/**
 * 1. 定位
 * 2. 路线规划
 * 3. 逆地址解析
 * 4. 模糊匹配关键词
 * 5，关键词搜索
 * 6. 获取省市区信息
 */


import {
  getSetting,         // 权限
  getLocation,        // 当前定位
  getCenterLocation,  // 获取中心点
  MoveToLocation,     // 移动中心点
  reverseAddr,        //  地址解析
  search,             // 关键词搜索
  Suggestion,         // 关键词提示
  showToast,          // 弹窗
  polyline,           // 路线
  Distance,           // 距离计算
  CityList,           // 城市列表
  ByCityId            // 省id获取市列表
} from "../tool/func";
const computedBehavior = require('miniprogram-computed')
var QQMapWX = require('../tool/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({
  behaviors: [computedBehavior],
  data: {
    longitude: '',
    latitude: '',
    keyword: '',
    key: 'HPJBZ-LFRR5-IKGIY-QSYX5-AMLES-U6BGY',
    latter: false,
    markers: [],
    distance: {},
    points: []
  },
  onReady: function (e) {
    this.mapCtx = wx.createMapContext('map')
  },
  onLoad: function (options) {
    const { key } = this.data;
    qqmapsdk = new QQMapWX({ key });
    this.getLocation()
  },
  computed: {
    // 时间格式化
    _Distance(data) {
      let val = data.distance.duration;
      let time = parseInt(val);  //秒
      let M = 0;  // 分
      let H = 0;  // 时
      if (time > 60) {
        M = parseInt(time / 60);
        time = parseInt(time % 60);
        if (M > 60) {
          H = parseInt(M / 60)
          M = parseInt(M % 60)
        }
      }
      let timer = '' //+ parseInt(time) + '秒'
      if (M > 0) timer = '' + parseInt(M) + '分钟' + timer;
      if (H > 0) timer = '' + parseInt(H) + "小时" + timer
      return timer;
    },
    _timerTip(data) {
      if (!data.distance.duration) {
        return false;
      }
      return true
    } 
  },
  // init 初始化信息
  async getLocation() {
    const { authSetting: auth } = await getSetting();
    if (!auth['scope.userLocation']) return
    const { longitude, latitude } = await getLocation({ type: 'gcj02' });
    let markers = [{
      id: 0,
      longitude,
      latitude,
      iconPath: '../../images/blue.png',
      width: 30,
      height: 30,
      callout: {
        content: '当前位置',
        fontSize: 13,
        borderRadius: 5,
        padding: 5,
        textAlign: 'center',
        color: '#000',
        bgColor: '#fff',
        display: 'ALWAYS',
        borderWidth: .5,
        borderColor: '#00BFFF',
      }
    }]
    let points = [{
      longitude,
      latitude,
    }]
    this.setData({
      markers,
      points,
      longitude,
      latitude
    })
  },
  // 模糊选中
  async handleItemSite(e) {
    let { addr } = e.currentTarget.dataset
    let params = {
      keyword: addr
    }
    const searchRes = await search(qqmapsdk, params);
    let { status, message, data } = searchRes;
    if (status !== 0) return await showToast({ title: '数据拉取失败' + message }, {}, 'mask');
    this.setData({ search_list: data, latter: true, query_list: [] })
  },
  // 关键词选中
  handleSelectItem(e) {
    let { location } = e.currentTarget.dataset
    this.setData({
      'points[1]': {
        longitude: location.lng,
        latitude: location.lat,
      },
      'markers[1]': {
        id: 1,
        longitude: location.lng,
        latitude: location.lat,
        iconPath: '../../images/red.png',
        width: 30,
        height: 30,
        callout: {
          content: '目标位置',
          fontSize: 13,
          borderRadius: 5,
          padding: 5,
          textAlign: 'center',
          color: '#000',
          bgColor: '#fff',
          display: 'ALWAYS',
          borderWidth: .5,
          borderColor: '#00BFFF',
        }
      }
    })
    this._polyline('', '', location.lat, location.lng)
  },
  // 防抖计时 
  Times: -1,
  // 关键字提示 *武汉市
  _Suggestion(e) {
    let { value: keyword } = e.detail;
    if (!keyword.trim()) {
      if (keyword == '') return this.setData({ query_list: [], search_list: [], distance: {} })
      return (async () => {
        await showToast({ title: '请填写正确内容！' }, {}, 'mask');
      })()
    }
    clearTimeout(this.Times);
    this.Times = setTimeout(async () => {
      let params = {
        keyword,
        region: '武汉市'
      }
      const tips = await Suggestion(qqmapsdk, params)
      let { status, message, data } = tips;
      if (status !== 0) return await showToast({ title: '搜索失败' + message }, {}, 'mask');
      this.setData({ query_list: data, latter: false, search_list: [] })
    }, 1000)
  },
  // 获取路线图
  async _polyline(Slat, Slng, Elat, Elng) {

    let params = this.common(Slat, Slng, Elat, Elng, 'polyline')

    const polylineRes = await polyline(qqmapsdk, params)
    if (polylineRes.status !== 0) return await showToast({ title: '查询失败' + searchRes.message }, {}, 'mask');
    let { result: { routes: [route] } } = polylineRes;
    let coors = route.polyline, poly = [];
    //坐标解压（返回的点串坐标，通过前向差分进行压缩）
    let kr = 1000000;
    for (var i = 2; i < coors.length; i++) {
      coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
    }
    //将解压后的坐标放入点串数组poly中
    for (var i = 0; i < coors.length; i += 2) {
      poly.push({ latitude: coors[i], longitude: coors[i + 1] })
    }
    this.setData({
      longitude: poly[0].longitude,
      latitude: poly[0].latitude,
      polyline: [{
        points: poly,
        color: '#FF0000DD',
        width: 4
      }]
    })
    this._getDistance(Slat, Slng, Elat, Elng)
  },
  // 计算距离
  async _getDistance(Slat, Slng, Elat, Elng) {
    let params = this.common(Slat, Slng, Elat, Elng, 'Distance')

    const distance = await Distance(qqmapsdk, params);
    let { status, message, result: { elements: [el] } } = distance;
    if (status !== 0) return await showToast({ title: '数据获取失败' + message }, {}, 'mask');
    this.setData({ distance: el })
  },
  // 城市列表
  async _getCityList() {
    const city = await CityList(qqmapsdk);
    let { status, message, result } = city;
    if (status !== 0) return await showToast({ title: '城市数据获取失败' + message }, {}, 'mask');
    this._reverseAddr()
  },
  // 城市 id 获取市级 数据
  async _byCityId(id) {
    let params = {
      id: '110000'
    }
    const city_node = await ByCityId(qqmapsdk, params)
    let { status, message, result } = city_node;
    if (status !== 0) return await showToast({ title: '数据获取失败' + message }, {}, 'mask');
    console.log(result)
  },
  // 解析地址
  async _reverseAddr(lat, lng) {
    let params = {
      // location: '30.708361,114.324187'
      location: lat + ',' + lng
    }
    console.log(params)
    const addr = await reverseAddr(qqmapsdk, params);
    let { status, message, result } = addr;
    if (status !== 0) return await showToast({ title: '地址解析失败！' + message }, {}, 'mask');
    this.setData({
      'markers[0]': { // 获取返回结果，放到mks数组中
        title: result.address,
        id: 0,
        latitude: result.location.lat,
        longitude: result.location.lng,
        iconPath: '../../images/red.png',//图标路径
        width: 20,
        height: 20,
        callout: { //在markers上展示地址名称，根据需求是否需要
          content: result.address,
          color: '#000',
          display: 'ALWAYS'
        },
        label: {
          content: result.title,
          color: '#000000',
          fontSize: 13,
          borderRadius: 10,
          bgColor: '#ffffff',
          padding: 5
        }
      },
      poi: {
        latitude: result.location.lat,
        longitude: result.location.lng
      }
    })
  },
  // 复用性函数
  common(Slat, Slng, Elat, Elng, flag) {
    let fromParams, toParams

    Slat && Slng ? fromParams = {
      latitude: Slat, longitude: Slng
    } : fromParams = ''

    Elat && Elng ?
      toParams = {
        latitude: Elat, longitude: Elng
      } : toParams = '';

    let params = {
      mode: 'driving',
      from: fromParams,
      to: flag === 'Distance' ? [toParams] : toParams
    }

    return params
  }
})